<template>
  <Layout>
    <div class="transfer-container">
      <el-card class="transfer-card">
        <template #header>
          <div class="card-header">
            <h3>转账汇款</h3>
          </div>
        </template>
        
        <!-- 转账方式选择 -->
        <el-tabs v-model="activeTab" class="transfer-tabs">
          
          <el-tab-pane label="银行卡转账" name="bankCard">
            <!-- 银行卡转账表单 -->
            <el-form 
              ref="bankCardFormRef"
              :model="bankCardForm"
              :rules="bankCardRules"
              label-width="120px"
              class="transfer-form"
            >
              <!-- 收款银行卡号 -->
              <el-form-item label="收款银行卡号" prop="targetCardNumber">
                <el-input 
                  v-model="bankCardForm.targetCardNumber"
                  placeholder="请输入收款人银行卡号"
                />
              </el-form-item>
              
              <!-- 转账金额 -->
              <el-form-item label="转账金额" prop="amount">
                <el-input-number
                  v-model="bankCardForm.amount"
                  :min="0.01"
                  :max="accountBalance > 0 ? accountBalance : undefined"
                  :precision="2"
                  :step="100"
                  style="width: 100%"
                  placeholder="请输入转账金额"
                />
                <div class="available-balance">可用余额: ¥ {{ formatAmount(accountBalance) }}</div>
              </el-form-item>
              
              <!-- 备注 -->
              <el-form-item label="备注" prop="remark">
                <el-input 
                  v-model="bankCardForm.remark"
                  placeholder="请输入转账备注（选填）"
                />
              </el-form-item>
              
              <!-- 支付密码 -->
              <el-form-item label="支付密码" prop="password">
                <el-input 
                  v-model="bankCardForm.password"
                  type="password"
                  placeholder="请输入支付密码"
                  show-password
                />
              </el-form-item>
              
              <el-form-item>
                <el-button type="primary" :loading="loading" @click="handleBankCardSubmit">
                  确认转账
                </el-button>
                <el-button @click="resetBankCardForm">重置</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          
          <el-tab-pane label="高级转账" name="advanced">
            <!-- 高级转账表单 -->
            <el-form 
              ref="advancedFormRef"
              :model="advancedForm"
              :rules="advancedRules"
              label-width="120px"
              class="transfer-form"
            >
              <el-alert
                type="info"
                :closable="false"
                show-icon
              >
                <div>
                  <p>高级转账支持多种方式找到收款人：</p>
                  <p>1. 用户名 + 身份证号</p>
                  <p>2. 用户名 + 手机号</p>
                  <p>请选择其中一种方式填写</p>
                </div>
              </el-alert>
              
              <!-- 收款人用户名 -->
              <el-form-item label="收款人用户名" prop="targetUsername">
                <el-input 
                  v-model="advancedForm.targetUsername"
                  placeholder="请输入收款人用户名"
                />
              </el-form-item>
              
              <!-- 高级验证方式 -->
              <el-form-item label="验证方式" prop="verificationType">
                <el-radio-group v-model="advancedForm.verificationType">
                  <el-radio label="idCard">身份证号</el-radio>
                  <el-radio label="phone">手机号</el-radio>
                </el-radio-group>
              </el-form-item>
              
              <!-- 收款人身份证号 -->
              <el-form-item 
                v-if="advancedForm.verificationType === 'idCard'" 
                label="身份证号" 
                prop="targetIdCard"
              >
                <el-input 
                  v-model="advancedForm.targetIdCard"
                  placeholder="请输入收款人身份证号"
                />
              </el-form-item>
              
              <!-- 收款人手机号 -->
              <el-form-item 
                v-if="advancedForm.verificationType === 'phone'" 
                label="手机号" 
                prop="targetPhone"
              >
                <el-input 
                  v-model="advancedForm.targetPhone"
                  placeholder="请输入收款人手机号"
                />
              </el-form-item>
              
              <!-- 转账金额 -->
              <el-form-item label="转账金额" prop="amount">
                <el-input-number
                  v-model="advancedForm.amount"
                  :min="0.01"
                  :max="accountBalance > 0 ? accountBalance : undefined"
                  :precision="2"
                  :step="100"
                  style="width: 100%"
                  placeholder="请输入转账金额"
                />
                <div class="available-balance">可用余额: ¥ {{ formatAmount(accountBalance) }}</div>
              </el-form-item>
              
              <!-- 备注 -->
              <el-form-item label="备注" prop="remark">
                <el-input 
                  v-model="advancedForm.remark"
                  placeholder="请输入转账备注（选填）"
                />
              </el-form-item>
              
              <!-- 支付密码 -->
              <el-form-item label="支付密码" prop="password">
                <el-input 
                  v-model="advancedForm.password"
                  type="password"
                  placeholder="请输入支付密码"
                  show-password
                />
              </el-form-item>
              
              <el-form-item>
                <el-button type="primary" :loading="loading" @click="handleAdvancedSubmit">
                  确认转账
                </el-button>
                <el-button @click="resetAdvancedForm">重置</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      
      <!-- 最近转账记录 -->
      <el-card class="recent-transfers-card">
        <template #header>
          <div class="card-header">
            <h3>最近转账记录</h3>
          </div>
        </template>
        
        <el-table 
          :data="recentTransfers"
          style="width: 100%"
          v-loading="historyLoading"
          empty-text="暂无转账记录"
        >
          <el-table-column prop="tradeNo" label="流水号" width="180" />
          <el-table-column prop="targetAccount" label="收款账号" width="150" />
          <el-table-column prop="amount" label="金额" width="120">
            <template #default="scope">
              <span class="expense">- {{ formatAmount(Math.abs(scope.row.amount)) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="statusName" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusTagType(scope.row.status)">
                {{ scope.row.statusName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" />
          <el-table-column prop="createTime" label="转账时间" width="180">
            <template #default="scope">
              {{ formatDateTime(scope.row.createTime) }}
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      
      <!-- 转账成功对话框 -->
      <el-dialog
        v-model="successDialogVisible"
        title="转账成功"
        width="30%"
        center
      >
        <div class="success-dialog">
          <el-icon class="success-icon"><CircleCheckFilled /></el-icon>
          <h2>转账成功</h2>
          <p>已成功向 {{ successDialogInfo.targetAccount }} 转账</p>
          <p class="success-amount">¥ {{ formatAmount(successDialogInfo.amount) }}</p>
          <p class="success-trade-no">交易流水号: {{ successDialogInfo.tradeNo }}</p>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="successDialogVisible = false">关闭</el-button>
            <el-button type="primary" @click="handleContinue">继续转账</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </Layout>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { usePageLifecycle } from '@/composables/usePageLifecycle';
import { CircleCheckFilled } from '@element-plus/icons-vue';
import { 
  advancedTransferAccount, 
  getAccountBalance 
} from '@/api/account';
import { getTransactionList } from '@/api/transaction';
import Layout from '@/components/layout/Layout.vue';

// 当前激活的标签页
const activeTab = ref('bankCard');

// 表单引用
const bankCardFormRef = ref(null);
const advancedFormRef = ref(null);

// 银行卡转账表单数据
const bankCardForm = reactive({
  targetCardNumber: '',
  amount: '',
  remark: '',
  password: ''
});

// 高级转账表单数据
const advancedForm = reactive({
  targetUsername: '',
  verificationType: 'idCard',
  targetIdCard: '',
  targetPhone: '',
  amount: '',
  remark: '',
  password: ''
});

// 状态变量
const loading = ref(false);
const historyLoading = ref(false);
const accountBalance = ref(0);
const recentTransfers = ref([]);
const successDialogVisible = ref(false);
const successDialogInfo = reactive({
  targetAccount: '',
  amount: '',
  tradeNo: ''
});

// 银行卡转账表单验证规则
const bankCardRules = {
  targetCardNumber: [
    { required: true, message: '请输入收款银行卡号', trigger: 'blur' },
    { pattern: /^\d{16,19}$/, message: '银行卡号格式不正确', trigger: 'blur' }
  ],
  amount: [
    { required: true, message: '请输入转账金额', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '转账金额必须大于0', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value > accountBalance.value) {
          callback(new Error('余额不足'));
        } else {
          callback();
        }
      }, 
      trigger: 'blur' 
    }
  ],
  password: [
    { required: true, message: '请输入支付密码', trigger: 'blur' },
    { min: 6, message: '支付密码长度不能少于6位', trigger: 'blur' }
  ]
};

// 高级转账表单验证规则
const advancedRules = {
  targetUsername: [
    { required: true, message: '请输入收款人用户名', trigger: 'blur' }
  ],
  verificationType: [
    { required: true, message: '请选择验证方式', trigger: 'change' }
  ],
  targetIdCard: [
    { 
      required: true, 
      message: '请输入收款人身份证号', 
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (advancedForm.verificationType === 'idCard' && !value) {
          callback(new Error('请输入收款人身份证号'));
        } else {
          callback();
        }
      }
    },
    { 
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, 
      message: '身份证号格式不正确', 
      trigger: 'blur' 
    }
  ],
  targetPhone: [
    { 
      required: true, 
      message: '请输入收款人手机号', 
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (advancedForm.verificationType === 'phone' && !value) {
          callback(new Error('请输入收款人手机号'));
        } else {
          callback();
        }
      }
    },
    { 
      pattern: /^1[3-9]\d{9}$/, 
      message: '手机号格式不正确', 
      trigger: 'blur' 
    }
  ],
  amount: [
    { required: true, message: '请输入转账金额', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '转账金额必须大于0', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value > accountBalance.value) {
          callback(new Error('余额不足'));
        } else {
          callback();
        }
      }, 
      trigger: 'blur' 
    }
  ],
  password: [
    { required: true, message: '请输入支付密码', trigger: 'blur' },
    { min: 6, message: '支付密码长度不能少于6位', trigger: 'blur' }
  ]
};

// 初始化页面数据
const initializePageData = async () => {
  console.log('Initializing transfer page data...');
  await Promise.all([
    fetchAccountBalance(),
    fetchRecentTransfers()
  ]);
};

// 使用页面生命周期 composable
const { safeLoadData } = usePageLifecycle(initializePageData, {
  autoLoad: true,
  reloadOnRouteChange: true,
  delay: 50
});

// 获取账户余额
const fetchAccountBalance = async () => {
  try {
    const response = await getAccountBalance();
    if (response.code === 0) {
      // 使用账户余额减去冻结金额得到可用余额
      accountBalance.value = response.data.balance - response.data.frozenAmount;
    }
  } catch (error) {
    console.error('获取账户余额失败:', error);
    ElMessage.error('获取账户余额失败，请刷新重试');
  }
};

// 获取最近转账记录
const fetchRecentTransfers = async () => {
  historyLoading.value = true;
  try {
    const response = await getTransactionList({
      tradeType: 3, // 转账类型
      pageNum: 1,
      pageSize: 10
    });
    if (response.code === 0) {
      recentTransfers.value = response.data || [];
    }
  } catch (error) {
    console.error('获取转账记录失败:', error);
    ElMessage.error('获取转账记录失败，请刷新重试');
  } finally {
    historyLoading.value = false;
  }
};

// 处理银行卡转账提交
const handleBankCardSubmit = async () => {
  if (!bankCardFormRef.value) return;
  
  await bankCardFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        // 构建银行卡转账请求数据
        const requestData = {
          targetCardNumber: bankCardForm.targetCardNumber,
          amount: bankCardForm.amount,
          remark: bankCardForm.remark,
          password: bankCardForm.password
        };
        
        // 注意：银行卡转账可能需要单独的API端点，这里使用高级转账API作为示例
        const response = await advancedTransferAccount(requestData);
        
        if (response.code === 0) {
          // 更新成功对话框信息
          successDialogInfo.targetAccount = '银行卡****' + bankCardForm.targetCardNumber.slice(-4);
          successDialogInfo.amount = bankCardForm.amount;
          successDialogInfo.tradeNo = response.data;
          
          ElMessage.success('转账成功');
          successDialogVisible.value = true;
          
          // 刷新数据
          await safeLoadData();
        }
      } catch (error) {
        console.error('转账失败:', error);
        ElMessage.error('转账失败，请重试');
      } finally {
        loading.value = false;
      }
    }
  });
};

// 处理高级转账提交
const handleAdvancedSubmit = async () => {
  if (!advancedFormRef.value) return;
  
  await advancedFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        // 构建请求参数
        const requestData = {
          targetUsername: advancedForm.targetUsername,
          amount: advancedForm.amount,
          remark: advancedForm.remark,
          password: advancedForm.password
        };
        
        // 根据验证方式添加不同的参数
        if (advancedForm.verificationType === 'idCard') {
          requestData.targetIdCard = advancedForm.targetIdCard;
        } else if (advancedForm.verificationType === 'phone') {
          requestData.targetPhone = advancedForm.targetPhone;
        }
        
        const response = await advancedTransferAccount(requestData);
        
        if (response.code === 0) {
          // 更新成功对话框信息
          successDialogInfo.targetAccount = advancedForm.targetUsername;
          successDialogInfo.amount = advancedForm.amount;
          successDialogInfo.tradeNo = response.data;
          
          ElMessage.success('转账成功');
          successDialogVisible.value = true;
          
          // 刷新数据
          await safeLoadData();
        }
      } catch (error) {
        console.error('转账失败:', error);
        ElMessage.error('转账失败，请重试');
      } finally {
        loading.value = false;
      }
    }
  });
};

// 重置银行卡转账表单
const resetBankCardForm = () => {
  if (bankCardFormRef.value) {
    bankCardFormRef.value.resetFields();
  }
};

// 重置高级转账表单
const resetAdvancedForm = () => {
  if (advancedFormRef.value) {
    advancedFormRef.value.resetFields();
  }
};

// 处理继续转账
const handleContinue = () => {
  // 根据当前激活的标签页重置相应的表单
  if (activeTab.value === 'bankCard') {
    resetBankCardForm();
  } else if (activeTab.value === 'advanced') {
    resetAdvancedForm();
  }
  
  successDialogVisible.value = false;
};

// 格式化金额
const formatAmount = (amount) => {
  if (amount === undefined || amount === null) return '0.00';
  return parseFloat(amount).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '暂无数据';
  
  const date = new Date(dateTimeStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 获取状态标签类型
const getStatusTagType = (status) => {
  const statusMap = {
    0: 'warning',   // 处理中
    1: 'success',   // 成功
    2: 'danger'     // 失败
  };
  return statusMap[status] || 'info';
};
</script>

<style scoped>
.transfer-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.transfer-tabs {
  width: 100%;
}

.transfer-form {
  max-width: 600px;
  margin: 20px auto 0;
}

.available-balance {
  margin-top: 5px;
  font-size: 12px;
  color: #909399;
  text-align: right;
}

.expense {
  color: #f56c6c;
}

.success-dialog {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.success-icon {
  font-size: 56px;
  color: #67c23a;
  margin-bottom: 16px;
}

.success-dialog h2 {
  margin: 10px 0;
  color: #303133;
}

.success-dialog p {
  margin: 5px 0;
  color: #606266;
}

.success-amount {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin: 10px 0;
}

.success-trade-no {
  font-size: 14px;
  color: #909399;
}

@media (max-width: 768px) {
  .transfer-form {
    width: 100%;
  }
}
</style>
